#include <iostream>
#include <string>
#include <vector>
// 中介者模式，行为型模式，用于降低多个对象和类之间的通信复杂性 
// 定义一个中介者接口，该接口包含了协调多个对象的方法
// 具体中介者类实现中介者接口，并对多个对象之间的交互进行控制
// 每个相关者都包含一个对中介者的引用，并在在需要与其他相关者进行交互时，通过中介者进行交互

// 中介者接口
class Mediator;

// 同事对象接口
class Colleague {
    public:
    explicit Colleague(Mediator* mediator,std::string name) : mediator_(mediator),name_(name) {}
    
    virtual void send(const std::string& message) = 0;
    virtual void receive(const std::string& message) = 0;

    protected:
    Mediator* mediator_;
    std::string name_;
};

// 中介者接口
class Mediator {
    public:
    virtual void mediate(const std::string& message,Colleague* sender) = 0;

};

// 具体中介者
class ConCreteMediator : public Mediator {
    public:
    void addColleague(Colleague* colleague) {
        colleagues_.push_back(colleague);
    }

    void mediate(const std::string& message,Colleague* sender) override {
        for (auto col : colleagues_) {
            if(col != sender) {
                col->receive(message);
            }
        }
    }
    private:
    std::vector< Colleague* > colleagues_;
};

// 具体同事对象
class ConcreteColleague : public Colleague {
    public:
    using Colleague::Colleague;

    void send(const std::string& message) override {
        std::cout << name_ << "Send message: " << message << std::endl;
        mediator_->mediate(message,this);
    }

    void receive(const std::string& message) override {
        std::cout << name_ << "Received message: " << message << std::endl;
    }
};

int main () {
    std::cout << "hello，中介者模式" << std::endl;
    ConCreteMediator mediator;

    ConcreteColleague colleague1(&mediator,"小明");
    ConcreteColleague colleague2(&mediator,"小二黑");

    mediator.addColleague(&colleague1);
    mediator.addColleague(&colleague2);

    colleague1.send("hello,小黑！你吃了吗？");

    std::cout << "\n";
    colleague2.send("Hi,我吃过了");
    return 0;
}